package com.tool.weixin.api;

import net.sf.json.JSONObject;

import org.slf4j.Logger;

import com.tool.weixin.model.TemplateMsg;
import com.tool.weixin.util.HttpUtils;

/**
 * 模板消息
 * @author huff
 *
 */
public class TemplateMsgApi {
	
	private static final Logger logger = org.slf4j.LoggerFactory.getLogger(TemplateMsgApi.class);
	
	private static final String template_msg_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";

	
	public static int send(TemplateMsg msg) {
		return send(AccessTokenApi.getAccessToken().getToken(), msg);
	}
	
	
	public static int send(String accessToken,TemplateMsg msg) {
		
		int result = 0;

		String url = template_msg_url.replace("ACCESS_TOKEN", accessToken);
		String jsonMenu = JSONObject.fromObject(msg).toString();
		JSONObject jsonObject = HttpUtils.httpRequest(url, "POST", jsonMenu);

		if (null != jsonObject) {
			if (0 != jsonObject.getInt("errcode")) {
				result = jsonObject.getInt("errcode");
				logger.error("发送模板消息失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
			}
		}
		return result;
	}
}
